package com.fauks.gmall.interceptor;

import com.alibaba.fastjson.JSON;
import com.fauks.gmall.annotation.LoginRequired;
import com.fauks.gmall.util.CookieUtil;
import com.fauks.gmall.util.HttpclientUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 登录拦截器
 */

@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod hm = (HandlerMethod) handler;
        LoginRequired loginRequired = hm.getMethodAnnotation(LoginRequired.class);
        if (loginRequired == null) {
            //没有添加注解不需要拦截直接放行
            return true;
        }
        //cookie中原有的token
        String oldToken = CookieUtil.getCookieValue(request, "oldToken", true);
        //请求带来的新token
        String newToken = request.getParameter("token");
        String token = "";
        if (!StringUtils.isEmpty(oldToken)) {
            //cookie中存在token，登录过
            token = oldToken;
        }
        if (!StringUtils.isEmpty(newToken)) {
            //可能是重新验证，也可能一直是该token
            token = newToken;
        }
        String tokenStatus = "fail";
        Map<String, String> tokenVerifyMap = null;
        if (!StringUtils.isEmpty(token)) {
            String nginxIp = request.getHeader("x-forwarded-for");
            if (StringUtils.isEmpty(nginxIp)) {
                nginxIp = request.getRemoteAddr();
            }
            if (StringUtils.isEmpty(nginxIp)) {
                nginxIp = "127.0.0.1";
            }
            //用http方式调用远程服务验证token
            String tokenVerifyResult = HttpclientUtil.doGet("http://localhost:8084/verifyToken?token=" + token + "&ip=" + nginxIp);
            tokenVerifyMap = JSON.parseObject(tokenVerifyResult, Map.class);
            tokenStatus = tokenVerifyMap.get("status");
        }
        //需要拦截
        boolean needLogin = loginRequired.isNeedLogin();
        if (needLogin) {
            //订单模块...必须验证身份才可以放行
            if (!"success".equals(tokenStatus)) {
                //token验证失败重定向到登录页，要传入登录后重定向的页面该url从request中获取
                StringBuffer requestURL = request.getRequestURL();
                response.sendRedirect("http://localhost:8084/index?ReturnUrl=" + requestURL);
                return false;
            }
            //token验证成功保存用户id等信息并放行
            request.setAttribute("memberId", tokenVerifyMap.get("memberId"));
            request.setAttribute("nickName", tokenVerifyMap.get("nickName"));
            //保存token到cookie
            if (!StringUtils.isEmpty(token)) {
                CookieUtil.setCookie(request, response, "oldToken", token, 60 * 60 * 2, true);
            }
        } else {
            //购物车模块...拦截后不登录也可以访问
            // 有些模块虽然不强制登录但是也需要验证cookie
            if ("success".equals(tokenStatus)) {
                request.setAttribute("memberId", tokenVerifyMap.get("memberId"));
                request.setAttribute("nickName", tokenVerifyMap.get("nickName"));
                //保存token到cookie
                if (!StringUtils.isEmpty(token)) {
                    CookieUtil.setCookie(request, response, "oldToken", token, 60 * 60 * 2, true);
                }
            }
        }
        return true;
    }
}
